import requests
import time
from datetime import datetime

def get_current_ip(max_retries=3, retry_delay=2):
    """获取当前公网IP地址，带重试机制
    
    Args:
        max_retries: 最大重试次数
        retry_delay: 重试间隔（秒）
    """
    # 使用更多可靠的IP查询服务
    services = [
        'https://api.ipify.org',
        'https://api.myip.com',  # 返回JSON格式
        'https://ip.seeip.org',
        'https://api.ip.sb/ip',
        'https://api64.ipify.org',  # IPv6兼容
        'https://ipinfo.io/ip'
    ]
    
    for service in services:
        for attempt in range(max_retries):
            try:
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                }
                response = requests.get(service, timeout=5, headers=headers)
                
                if response.status_code == 200:
                    if service == 'https://api.myip.com':
                        return response.json()['ip'].strip()
                    return response.text.strip()
                
            except requests.RequestException as e:
                print(f"服务 {service} 尝试 {attempt + 1}/{max_retries} 失败: {str(e)}")
                if attempt < max_retries - 1:
                    time.sleep(retry_delay)
                continue
            except ValueError as e:
                print(f"解析响应失败 {service}: {str(e)}")
                continue
            
    print("所有IP查询服务均失败")
    return None

def main():
    print("开始测试IP变换速度...")
    print("测试时长：1分钟")
    print("正在进行初始IP检测...")
    
    start_time = time.time()
    end_time = start_time + 60  # 运行1分钟
    
    ip_changes = []
    last_ip = None
    failed_checks = 0
    max_failed_checks = 3  # 连续失败次数阈值
    
    # 确保获取到初始IP
    while last_ip is None and time.time() < end_time:
        last_ip = get_current_ip(max_retries=3, retry_delay=1)
        if last_ip:
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"初始IP: {last_ip} - {current_time}")
        else:
            print("初始IP检测失败，重试中...")
            time.sleep(2)
    
    if not last_ip:
        print("无法获取IP地址，请检查网络连接")
        return
    
    print("\n开始监测IP变化...")
    while time.time() < end_time:
        current_ip = get_current_ip(max_retries=2, retry_delay=1)
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        if current_ip:
            failed_checks = 0  # 重置失败计数
            if current_ip != last_ip:
                ip_changes.append((current_ip, current_time))
                print(f"检测到IP变化: {last_ip} -> {current_ip} - {current_time}")
                last_ip = current_ip
        else:
            failed_checks += 1
            print(f"第 {failed_checks} 次检测失败")
            if failed_checks >= max_failed_checks:
                print("\n连续多次检测失败，请检查网络连接")
                break
        
        time.sleep(2)  # 降低检查频率，避免被服务器限制
    
    # 输出统计结果
    total_changes = len(ip_changes)
    print("\n测试结果:")
    print(f"1分钟内IP变化次数: {total_changes}")
    print(f"平均每次变化间隔: {60/total_changes if total_changes > 0 else 'N/A'} 秒")
    
    if ip_changes:
        print("\nIP变化记录:")
        for ip, timestamp in ip_changes:
            print(f"{timestamp}: {ip}")

if __name__ == "__main__":
    main()